package utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.filechooser.FileFilter;

/**
 * Class used by us to filter files when loading or saving projects, test results file and output jar component.
 *
 * @author Andy Cullache
 */
public class Filter extends FileFilter {

    private String description;
    private List<String> extensions;

    /**
     * Principal constructor. Set the description.
     * 
     * @param description      Description of the extension to filter.
     */
    public Filter(String description) {
        if (description == null) {
            throw new NullPointerException("The description can not be null.");
        }
        this.description = description;
        this.extensions = new ArrayList<String>();
    }

    /**
     * Whether the given file is accepted by this filter. 
     * 
     * @param file      Whether the given file is accepted by this filter.
     * @return      True if the file extension meets. False otherwise.
     */
    public boolean accept(File file) {
        if (file.isDirectory() || extensions.size() == 0) {
            return true;
        }
        String fileName = file.getName().toLowerCase();
        for (String extension : extensions) {
            if (fileName.endsWith(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * The description of this filter. For example: "JPG and GIF Images".
     * 
     * @return      Description of extension.
     */
    public String getDescription() {
        StringBuffer buffer = new StringBuffer(description);
        buffer.append(" (");
        for (String extension : extensions) {
            buffer.append(extension).append(" ");
        }
        return buffer.append(")").toString();
    }
    

    /**
     * Add an extension to the list of extensions to the current description.
     * 
     * @param extension      Extension to add.
     */
    public void addExtension(String extension) {
        if (extension == null) {
            throw new NullPointerException("The extension can not be null..");
        }
        extensions.add(extension);
    }
}
